# -*- coding: utf-8 -*- 
"""
@Author: 孟颖
@email: 652044581@qq.com
@date: 2023/5/5 10:04
@desc:  定时器插件
"""

from sanic import Sanic
from sanic.response import json
from sanic import Blueprint
from sanic.views import HTTPMethodView
from sanic_scheduler import SanicScheduler, make_task, task
from datetime import timedelta, time


app = Sanic(__name__)

# 注册蓝图
DemoBlueprint = Blueprint('demo', url_prefix='/demo')

# 定时器任务/支持同步方法和异步方法, 必须接收一个参数app
async def cron_job(app):
    print("cron_job started")


# 引入定时器任务
scheduler = SanicScheduler(app)

# 在2:30之后每2秒运行一次函数
# make_task(cron_job, period=timedelta(seconds=2), start=time(hour=2, minute=30))

# 在10秒后每2秒运行一次函数
# make_task(cron_job, period=timedelta(seconds=2), start=timedelta(seconds=10))

# 装饰器的方式执行
@task(period=timedelta(seconds=2), start=timedelta(seconds=10))
async def cron_job2(app):
    print("cron_job2 started")

class SyncTestView(HTTPMethodView):
    def get(self, request):
        return json({"ctx":"params"})


DemoBlueprint.add_route(SyncTestView.as_view(), "/sync")

app.blueprint(DemoBlueprint)

if __name__ == "__main__":
    app.run(host="localhost", port=8000)
